/**
 * 设置元素可见性
 * @param element
 * @param isShow
 */
export function setElementVisible(element: HTMLElement, isShow: boolean) {
  element.style.display = isShow ? '' : 'none'
}

type Direction = 'up' | 'down' | 'left' | 'right'
/**
 * 监听滑动事件
 * @param callback
 *
 */
export function addSlidingEventListener(
  callback: (direction: Direction) => void
) {
  // https://juejin.cn/post/6973541673196322847
  let box = document.querySelector('body')! // 监听对象
  let startTime = 0 // 触摸开始时间
  let startDistanceX = 0 // 触摸开始X轴位置
  let startDistanceY = 0 // 触摸开始Y轴位置
  let endTime = 0 // 触摸结束时间
  let endDistanceX = 0 // 触摸结束X轴位置
  let endDistanceY = 0 // 触摸结束Y轴位置
  let moveTime = 0 // 触摸时间
  let moveDistanceX = 0 // 触摸移动X轴距离
  let moveDistanceY = 0 // 触摸移动Y轴距离
  box.addEventListener('touchstart', (e) => {
    startTime = new Date().getTime()
    startDistanceX = e.touches[0].screenX
    startDistanceY = e.touches[0].screenY
  })
  box.addEventListener('touchend', (e) => {
    endTime = new Date().getTime()
    endDistanceX = e.changedTouches[0].screenX
    endDistanceY = e.changedTouches[0].screenY
    moveTime = endTime - startTime
    moveDistanceX = startDistanceX - endDistanceX
    moveDistanceY = startDistanceY - endDistanceY
    console.log(moveDistanceX, moveDistanceY)
    // 判断滑动距离超过40 且 时间小于500毫秒
    if (
      (Math.abs(moveDistanceX) > 40 || Math.abs(moveDistanceY) > 40) &&
      moveTime < 500
    ) {
      // 判断X轴移动的距离是否大于Y轴移动的距离
      if (Math.abs(moveDistanceX) > Math.abs(moveDistanceY)) {
        // 左右
        // console.log(moveDistanceX > 0 ? '左' : '右')
        if (moveDistanceX > 0) {
          callback('left')
        } else {
          callback('right')
        }
      } else {
        // 上下
        // console.log(moveDistanceY > 0 ? '上' : '下')
        if (moveDistanceY > 0) {
          callback('up')
        } else {
          callback('down')
        }
      }
    }
  })
}
